package com.zjw.algorithm.ready1;

import com.zjw.algorithm.utils.TreeNode;

public class _二叉树的剪枝 {

    public TreeNode pruneTree(TreeNode root) {
        return dfs(root, null) ? root : null;
    }

    private boolean dfs(TreeNode root, TreeNode parent) {
        if (root == null) {
            //当没有遇到1
            return false;
        }

        boolean findNumberOne = (dfs(root.left, root) | dfs(root.right, root)) || root.val == 1;

        if (!findNumberOne && parent != null) {
            if (parent.left == root) {
                parent.left = null;
            }
            if (parent.right == root) {
                parent.right = null;
            }
        }
        return findNumberOne;
    }
}
